﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CoderJoe
{
    public partial class SampleService2
        : ServiceBase
    {
        protected SampleModelContainer Context { get; private set; }
        protected int PlatformId { get; private set; }
        protected Platform Platform { get; private set; }

        protected SampleService2()
        {
        }

        public SampleService2(SampleModelContainer context, int platformId)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            Context = context;
            PlatformId = platformId;
        }

        public SampleService2(SampleModelContainer context, Platform platform)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            if (platform == null)
                throw new ArgumentNullException("platform");

            Context = context;
            Platform = platform;
            PlatformId = platform.PlatformId;
        }

        protected override IDisposable CreateServiceContext()
        {
            Context = new SampleModelContainer();

            return new DisposableContainer(
                Context);
        }

        public IEnumerable<User> FindUsers()
        {
            ValidatePlatform();

            return
                (from u in Context.Users
                 where u.Platforms.Contains(Platform)
                 select u);
        }

        private void ValidatePlatform()
        {
            if (Platform != null)
            {
                Platform =
                    (from p in Context.Platforms
                     where p.PlatformId == PlatformId
                     select p).FirstOrDefault();
            }

            if (Platform == null)
                throw new Exception("Invalid Platform");
        }
    }
}
